package com.uit.trip.tab_activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.facebook.Request;
import com.facebook.Request.Callback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.uit.trip.R;
import com.uit.trip.TripApplication;
import com.uit.trip.bridge.Parser;
import com.uit.trip.bridge.Server;
import com.uit.trip.lazyloading.ImageLoader;
import com.uit.trip.models.Trip;
import com.uit.trip.models.User;
import com.uit.trip.service.LocationService;
import com.uit.trip.tab_activity.childs.CommentActivity;
import com.uit.trip.tab_activity.childs.Form_PostActivity;
import com.uit.trip.utils.FileCommon;
import com.uit.trip.utils.IconContextMenu;
import com.uit.trip.utils.ShareTwitter;
import com.uit.trip.utils.IconContextMenu.IconContextMenuOnClickListener;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Tab_TripHomeActivity extends ListActivity {

	// Use for select image
	private static final int PROGRESSBAR_MAX = 100000;
	private static final int DIALOG_GALLERY = 0;
	private static final int DIALOG_CAMERA = 1;
	private static final int DIALOG_SHARE = 2;
	private static final int GALLERY_REQUESTCODE = 10;
	private static final int CAMERA_REQUESTCODE = 12;
	private static final int FORM_POST_REQUESTCODE = 11;
	private static final int MEDIA_TYPE_IMAGE = 1;
	public static final int SHARE_FACEBOOK = 13;
	public static final int SHARE_TWITTER = 14;
	public static final int SHARE_EMAIL = 15;
	private static String mSelectedImagePath;
	public static Bitmap bitmap;

	// Declare Models
	private Server server;
	private User fbUser;
	private TripAdapter adapter;
	private ImageReceiver imageReceiver;
	private PostImageReceiver postImageReceiver;
	private PostUserInfoReceiver postUserInfoReceiver;
	private TextView userName;
	private ProgressBar progressBar;
	private Button btLoadMore;
	private ImageButton btRefresh;
	private IconContextMenu iconContextMenu;
	public static final String NEW_IMAGELIST_FOUND = "new";
	public static final String POST_IMAGE_FINISH = "image";
	public static final String POST_USERINFO_FINISH = "user";

	private List<Trip> tripList;
	private int currentTripPosition = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.tab_home);

		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		userName = (TextView) findViewById(R.id.tvUserName);
		btRefresh = (ImageButton) this.findViewById(R.id.refresh);
		fbUser = new User();
		server = new Server(this);
		tripList = new ArrayList<Trip>();
		imageReceiver = new ImageReceiver();
		postImageReceiver = new PostImageReceiver();
		postUserInfoReceiver = new PostUserInfoReceiver();
		iconContextMenu = new IconContextMenu(Tab_TripHomeActivity.this,
				DIALOG_SHARE);
		iconContextMenu.setOnClickListener(onIconContextMenuClick);

		// Add footer load more
		LayoutInflater inflater = getLayoutInflater();
		View footerView = inflater.inflate(R.layout.row_footer_loadmore,
				getListView(), false);
		getListView().addFooterView(footerView);
		btLoadMore = (Button) footerView.findViewById(R.id.btLoadMore);
		btLoadMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Toast toast = Toast.makeText(getApplicationContext(),
						"Load more here", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
				toast.show();
				// Get more
				if (tripList.size() > 0) {
					int index = tripList.size() - 1;
					if (fbUser != null)
						getListImages(tripList.get(index).imgId, fbUser.userId);// 100000524155533
				}
			}
		});

		startProgressBar();
		getUserInfo();
		adapter = new TripAdapter();
		setListAdapter(adapter);
		startService(new Intent(this, LocationService.class));
	}

	private void startProgressBar() {
		getListView().setVisibility(View.GONE);
		RelativeLayout layout = (RelativeLayout) findViewById(R.id.progressFrame);
		layout.setVisibility(View.VISIBLE);
		progressBar.setProgress(0);
		progressBar.setMax(PROGRESSBAR_MAX);
		btLoadMore.setVisibility(View.GONE);
	}

	private void stopProgressBar() {
		getListView().setVisibility(View.VISIBLE);
		RelativeLayout layout = (RelativeLayout) findViewById(R.id.progressFrame);
		layout.setVisibility(View.GONE);
		progressBar.setProgress(PROGRESSBAR_MAX);
		btLoadMore.setVisibility(View.VISIBLE);
	}

	private void hideListView() {
		btLoadMore.setVisibility(View.GONE);
		getListView().setVisibility(View.GONE);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		return super.onContextItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		adapter.notifyDataSetChanged();
		registerReceiver(imageReceiver, new IntentFilter(NEW_IMAGELIST_FOUND));
		registerReceiver(postImageReceiver, new IntentFilter(POST_IMAGE_FINISH));
		registerReceiver(postUserInfoReceiver, new IntentFilter(
				POST_USERINFO_FINISH));
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(imageReceiver);
		unregisterReceiver(postImageReceiver);
		unregisterReceiver(postUserInfoReceiver);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		final Dialog dialog = new Dialog(this);
		switch (id) {
		case DIALOG_GALLERY:
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.dialog_camera);
			// dialog.setTitle("Take a photo");
			LinearLayout camera = (LinearLayout) dialog
					.findViewById(R.id.camera_dialog);
			LinearLayout gallery = (LinearLayout) dialog
					.findViewById(R.id.gallery_dialog);
			camera.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					dialog.dismiss();
					showDialogCamera();
				}
			});

			gallery.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					dialog.dismiss();
					Intent i = new Intent(Intent.ACTION_GET_CONTENT);
					i.setType("image/*");
					startActivityForResult(
							Intent.createChooser(i, "Select image"),
							GALLERY_REQUESTCODE);
				}
			});
			return dialog;
		case DIALOG_SHARE:
			iconContextMenu.addItem(getResources(), "Facebook",
					R.drawable.icon_face, SHARE_FACEBOOK);
			iconContextMenu.addItem(getResources(), "Twitter",
					R.drawable.icon_twitle, SHARE_TWITTER);
			iconContextMenu.addItem(getResources(), "Email",
					R.drawable.icon_mail, SHARE_EMAIL);
			return iconContextMenu.createMenu("Share picture via:");

		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	private void showDialogCamera() {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Tab_TripHomeActivity.this);
		builder.setTitle("Camera");
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setMessage("You should put your device in landcape mode")
				.setCancelable(true)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Uri mCapturedImageURI = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
						getContentResolver().notifyChange(mCapturedImageURI,
								null);
						Intent intent = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);
						intent.putExtra(MediaStore.EXTRA_OUTPUT,
								mCapturedImageURI);
						startActivityForResult(intent, CAMERA_REQUESTCODE);
					}
				});
		builder.create().show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case GALLERY_REQUESTCODE:
				Uri imgUri = data.getData();
				mSelectedImagePath = getPath(imgUri);
				Intent i = new Intent(this, Form_PostActivity.class);
				i.putExtra("imagepath", mSelectedImagePath);

				startActivityForResult(i, FORM_POST_REQUESTCODE);
				break;
			case FORM_POST_REQUESTCODE:
				Toast.makeText(this, "Your photo is uploading...",
						Toast.LENGTH_SHORT).show();
				break;

			case CAMERA_REQUESTCODE:
				Intent intent = new Intent(this, Form_PostActivity.class);
				intent.putExtra("imagepath", mSelectedImagePath);
				startActivityForResult(intent, FORM_POST_REQUESTCODE);
				break;
			default:
				break;
			}
		}
	}

	/*
	 * Header action
	 */
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.camera:
			showDialog(DIALOG_GALLERY);
			break;
		case R.id.refresh:
			btRefresh.setEnabled(false);
			adapter.imageLoader.clearCache();
			tripList.clear();
			startProgressBar();
			getListImages("0", fbUser.userId);
			break;
		default:
			break;
		}
	}

	/*
	 * 
	 */

	/*
	 * getUserInfo
	 * 
	 * Get the user info when user login facebook
	 * 
	 * Send the info to server
	 */
	private void getUserInfo() {
		final Session session = Session.getActiveSession();
		if (session != null && session.isOpened()) {
			Request request = Request.newMeRequest(session,
					new Request.GraphUserCallback() {

						public void onCompleted(GraphUser user,
								Response response) {
							// TODO Auto-generated method stub
							if (session == Session.getActiveSession()) {
								if (user != null) {
									fbUser = new User(user.getId(), user
											.getName());
									userName.setText(fbUser.userName);
									TripApplication app = (TripApplication) getApplication();
									app.setUser(fbUser);
									TextView tvStatus = (TextView) findViewById(R.id.tvStatus);
									tvStatus.setText("Get data from server...");
									Log.i("duongnx", "getUserInfo:success");
									server.postUserInfo(fbUser.userId,
											fbUser.userName, "null");
								} else {
									stopProgressBar();
									Log.i("duongnx", "getUserInfo:null");
								}
							}
						}
					});
			Request.executeBatchAsync(request);
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
	}

	/*
	 * 
	 */
	public void getListImages(String imgId, String userId) {
		server.getListImages(imgId, userId);
	}

	// public void getFriends() {
	// String query =
	// "SELECT uid, name, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())";
	// Bundle params = new Bundle();
	// params.putString("q", query);
	// Session session = Session.getActiveSession();
	// Request request = new Request(session, "/fql", params, HttpMethod.GET,
	// new Request.Callback() {
	// public void onCompleted(Response response) {
	// Log.i("duongnx", "Result: " + response.toString());
	// }
	// });
	// Request.executeBatchAsync(request);
	// Log.i("duongnx", "getFiends");
	// }

	/*
	 * Get Image's path from Uri when get Image from gallery.
	 */
	private String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	private static Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(MEDIA_TYPE_IMAGE));
	}

	private static File getOutputMediaFile(int type) {
		File mediaFile;
		File mediaStorageDir = new File(
				Environment.getExternalStorageDirectory(), "TripTracker");
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				return null;
			}
		}

		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		mSelectedImagePath = mediaStorageDir.getPath() + File.separator
				+ "IMG_" + timeStamp + ".png";
		if (type == Tab_TripHomeActivity.MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mSelectedImagePath);
			if (!mediaFile.exists()) {
				// return null;
			}
		} else {
			return null;
		}
		return mediaFile;
	}

	public class TripAdapter extends BaseAdapter {

		public ImageLoader imageLoader = new ImageLoader(
				getApplicationContext());

		public int getCount() {
			// TODO Auto-generated method stub
			return tripList.size();
		}

		public Object getItem(int id) {
			// TODO Auto-generated method stub
			return tripList.get(id);
		}

		public long getItemId(int index) {
			// TODO Auto-generated method stub
			return index;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final int _position = position;
			final Trip trip = tripList.get(position);
			LayoutInflater inflater = getLayoutInflater();

			if (convertView == null) {
				convertView = inflater
						.inflate(R.layout.row_item, parent, false);
			}
			ImageView imgContent = (ImageView) convertView
					.findViewById(R.id.img_content);
			// if (trip.bitmap != null) {
			// imgContent.setImageBitmap(trip.bitmap);
			// } else {
			// imgContent.setImageResource(R.drawable.no_image);
			// }
			// Log.i("duongnx", trip.imgName);
			if (trip.link != null && !trip.link.equals("")) {
				// trip.isLoading = true;
				String link = trip.link;
				// Log.i("duongnx", link);
				// link = link.replace("localhost", "192.168.0.103");
				// new ImageLoadTask(position).execute(link);
				trip.bitmap = imageLoader.DisplayImage(link, imgContent);
			}

			TextView user = (TextView) convertView.findViewById(R.id.tvUser);
			user.setText(trip.userName);
			TextView time = (TextView) convertView.findViewById(R.id.tvTime);
			time.setText(trip.time);

			ImageButton btComment = (ImageButton) convertView
					.findViewById(R.id.btComment);
			ImageButton btShare = (ImageButton) convertView
					.findViewById(R.id.btShare);
			final ImageButton btLike = (ImageButton) convertView
					.findViewById(R.id.btLike);

			final int index = position;
			if (trip.isLike == 1) {
				btLike.setEnabled(false);
				btLike.setImageResource(R.drawable.like_red);
			} else {
				btLike.setEnabled(true);
				btLike.setImageResource(R.drawable.like);
			}

			btComment.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					// TODO Auto-generated method stub
					adapter.notifyDataSetChanged();
					Intent i = new Intent(getApplicationContext(),
							CommentActivity.class);
					i.putExtra("position", index);
					i.putExtra("type", TripApplication.TYPE_HOME);
					startActivity(i);
				}
			});

			btShare.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					currentTripPosition = _position;
					showDialog(DIALOG_SHARE);
				}
			});

			btLike.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					trip.isLike = 1;
					btLike.setEnabled(false);
					btLike.setImageResource(R.drawable.like_red);
					server.postLike(trip.imgId, fbUser.userId);
				}
			});

			imgContent.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					adapter.notifyDataSetChanged();
					Intent i = new Intent(getApplicationContext(),
							CommentActivity.class);
					i.putExtra("position", index);
					i.putExtra("type", TripApplication.TYPE_HOME);
					startActivity(i);
				}
			});

			return convertView;
		}
	}

	/*
	 * When down load data succuess
	 * 
	 * Will fire here to updat listview
	 */
	public class ImageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			stopProgressBar();
			btRefresh.setEnabled(true);

			Bundle extras = intent.getExtras();
			if (extras == null) {
				return;
			}
			String response = extras.getString("response");
			if (response == null || response.equals("")) {
				// Lay danh sach bi loi
				hideListView();
			} else {
				List<Trip> _tripList = new ArrayList<Trip>();
				_tripList = Parser.parseImageList(response);
				for (int i = 0; i < _tripList.size(); i++) {
					tripList.add(_tripList.get(i));
				}
				TripApplication application = (TripApplication) getApplication();
				application.setTripList(tripList, TripApplication.TYPE_HOME);
				adapter.notifyDataSetChanged();
			}
		}
	}

	/*
	 * Thong bao khi upload image finishss
	 */
	public class PostImageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub

			Bundle extras = intent.getExtras();
			if (extras == null) {
				return;
			}
			Boolean isUploadSuccess = extras.getBoolean("result");
			if (isUploadSuccess) {
				Toast.makeText(getApplicationContext(), "Upload image success",
						Toast.LENGTH_SHORT).show();

				Trip trip = new Trip(fbUser.userId, extras.getString("imgId"),
						fbUser.userName, extras.getString("description"),
						extras.getString("link"), extras.getString("la"),
						extras.getString("lng"), extras.getString("date"), 0);

				tripList.add(0, trip);
				adapter.notifyDataSetChanged();
			} else {
				Toast.makeText(getApplicationContext(), "Upload photo fail",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	public class PostUserInfoReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			Log.i("duongnx", "PostUserInfoReceiver:");
			Bundle extras = intent.getExtras();
			if (extras == null)
				return;
			Boolean isSuccess = extras.getBoolean("result");
			if (isSuccess) {
				getListImages("0", fbUser.userId);
			} else {
				stopProgressBar();
				Toast.makeText(getApplicationContext(), "Post userInfo fail",
						Toast.LENGTH_LONG).show();
			}
		}

	}

	IconContextMenuOnClickListener onIconContextMenuClick = new IconContextMenuOnClickListener() {

		@Override
		public void onClick(int menuId) {
			// TODO Auto-generated method stub
			Trip trip = null;
			if (currentTripPosition > -1
					&& currentTripPosition < tripList.size()) {
				trip = tripList.get(currentTripPosition);
			}
			switch (menuId) {
			case SHARE_FACEBOOK:
				if (appInstalledOrNot("com.facebook.katana")) {

					if (trip != null) {
						Toast.makeText(getApplicationContext(),
								"Your photo is uploading...",
								Toast.LENGTH_SHORT).show();
						sharePhotoToFacebook(trip.imgId);
					} else {
						Toast.makeText(getApplicationContext(),
								"Can not share. Please try again",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(getApplicationContext(),
							"Please install Facebook app first",
							Toast.LENGTH_SHORT).show();
				}

				break;
			case SHARE_TWITTER:
				Toast.makeText(getApplicationContext(), "Share Twitter...",
						Toast.LENGTH_SHORT).show();
				ShareTwitter twitter = new ShareTwitter(
						Tab_TripHomeActivity.this);
				twitter.sharePhotoViaTwitter(trip.imgId);
				break;

			case SHARE_EMAIL:
				Toast.makeText(getApplicationContext(), "Share Email...",
						Toast.LENGTH_SHORT).show();
				sharePhotoViaEmail(trip.bitmap);
				break;

			default:
				break;
			}
			currentTripPosition = -1;
		}
	};

	private boolean appInstalledOrNot(String uri) {
		PackageManager pm = getPackageManager();
		boolean app_installed = false;
		try {
			pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
			app_installed = true;
		} catch (PackageManager.NameNotFoundException e) {
			app_installed = false;
		}
		return app_installed;
	}

	private void sharePhotoToFacebook(String imgID) {
		String link = Server.LINKSHARE + imgID;
		final Session session = Session.getActiveSession();
		if (session != null && session.isOpened()) {
			Request request = Request.newStatusUpdateRequest(session,
					fbUser.userName + " share:", new Callback() {

						@Override
						public void onCompleted(Response response) {
							// TODO Auto-generated method stub
							if (response == null) {
								Toast.makeText(getApplicationContext(),
										"Share fail", Toast.LENGTH_SHORT)
										.show();
								return;
							}
							String result = response.toString();
							String s = response.getGraphObject().toString();
							Log.i("duongnx", "graph Object:" + s);
							if (result.contains("200")) {
								Toast.makeText(getApplicationContext(),
										"Share success", Toast.LENGTH_SHORT)
										.show();
							} else {
								Toast.makeText(getApplicationContext(),
										"Share fail", Toast.LENGTH_SHORT)
										.show();
							}
						}
					});

			Bundle params = request.getParameters();
			params.putString("link", link);

			request.setParameters(params);
			// server.postImageToFacebook(bitmap, session.getAccessToken());
			Request.executeBatchAsync(request);
		}
	}

	public void sharePhotoViaEmail(Bitmap bitmap) {
		// B1: lay duong dan luu anh
		String mPath = FileCommon.getOutputFile();
		// B2: Luu anh
		if (mPath != null && !mPath.equalsIgnoreCase("")) {
			FileCommon.saveImageFile(this, bitmap);
			// Send anh
			sendEmailImageFile(mPath);
		}
	}

	private void sendEmailImageFile(String pPathImage) {

		Uri iData = FileCommon.getOutputMediaFileUri(pPathImage);
		try {
			Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
			emailIntent.setType("message/rfc822");
			emailIntent.putExtra(Intent.EXTRA_STREAM, iData);

			startActivityForResult((Intent.createChooser(emailIntent,
					"Choose an Email client:")),
					Tab_TripHomeActivity.SHARE_EMAIL);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "Your device doesn't support to send email! ",
					Toast.LENGTH_LONG).show();
		}
	}
}